<template>
  <div>
    <div class="analysisGeneration-content1">
      <el-form :model="propsData" ref="analysisGeneration-content1" class="analysisGeneration-content1-form">
        <el-form-item label="表名" prop="tableName" class="s" :rules="[{ required: true, message: '请输入表名', trigger: 'blur' }]">
          <el-input placeholder="表名" v-model="propsData.tableName" clearable @change="toEn(propsData.tableName,1)"/>
        </el-form-item>
        <el-form-item label="英文表名字" prop="enTableName" class="s" :rules="[{ required: true, message: '请输入英文表名字', trigger: 'blur' }]">
          <el-input placeholder="英文表名字" v-model="propsData.enTableName" clearable style="width: 550px"/>
        </el-form-item>
      </el-form>
    </div>

    <div class="analysisGeneration-content2">
      <span class="s">字段解析</span>
      <el-input v-model="propsData.tableDataParsing" placeholder="请输入字段解析、号隔开" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" clearable class="mr-12 "></el-input>
      <el-button type="primary" @click="startParsingClick">开始翻译</el-button>
    </div>


    <div class="analysisGeneration-content3">
      <img style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
      <el-input v-model="captcha" placeholder="请输入验证码" clearable style="width: 110px;margin: 0 12px"/>
      <el-button type="success" size="medium" @click="login">登录</el-button>
      <el-button type="success" size="medium" @click="generatePageCodeClick">提交到数据库</el-button>
      <el-button type="danger" size="medium" @click="initializationClcik">初始化</el-button>
    </div>


    <div>
      <el-table ref="table" :data="propsData.fieldArray" border style="width: 100%;margin-top: 15px"
                :header-cell-style="{background:'#f5f7fa',color:'#081333',fontWeight: 'normal'}">
        <el-table-column label="中文字段" :show-overflow-tooltip="true" align="center" prop="zhData">
        </el-table-column>
        <el-table-column label="英文字段" :show-overflow-tooltip="true" align="center" prop="enData">
          <template slot-scope="scope">
            <el-input v-model="scope.row.enData" placeholder="请输入英文字段" clearable></el-input>
          </template>
        </el-table-column>
        <el-table-column label="字段类型" :show-overflow-tooltip="true" align="center" prop="dbType">
          <template slot-scope="scope">
            <el-select v-model="scope.row.dbType" placeholder="请选择字段类型" @change="dbTypeChange(scope.row)">
              <el-option
                  v-for="item in dbTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字段长度" :show-overflow-tooltip="true" align="center" prop="dbLength">
          <template slot-scope="scope">
            <el-input v-model="scope.row.dbLength" placeholder="请输入字段长度" clearable></el-input>
          </template>
        </el-table-column>


      </el-table>
    </div>
  </div>
</template>

<script>
import md5 from 'js-md5';
import {jsonp} from 'vue-jsonp';

export default {
  components: {},
  props: [],
  data() {
    return {
      randCodeImage: '',//登录验证码图片
      captcha: '',//验证码
      currdatetime: '',//登录时间戳
      dbTypeOption: [
        {label: 'String', value: 'string'}, //默认长度255
        {label: 'Datetime', value: 'Datetime'},//默认长度 0
        {label: 'Double', value: 'double'}, //默认长度10
        {label: 'Integer/Boolean', value: 'int'}, //默认长度10
        // {label: 'Boolean', value: 'int'}, //默认长度10 布尔型用int代替
      ],
      propsData: {
        tableName: '',//表名
        enTableName: '',//英文表
        tableDataParsing: '',//字段解析
        fieldArray: [
          /*{
            zhData: dataParsing[i],
            enData: res
          }*/
        ],//解析后的字段
      }
    };
  },
  mounted() {
    this.handleChangeCheckCode();
  },
  methods: {
    // 获取验证码
    handleChangeCheckCode() {
      this.currdatetime = new Date().getTime();
      this.$sysrandomImage(this.currdatetime).then((result) => {
        this.randCodeImage = result.result
      })
    },
    // 登录
    login() {
      let data = {
        password: "123456",
        remember_me: true,
        username: "admin",
        captcha: this.captcha,
        checkKey: this.currdatetime
      }
      this.$nbcioLogin(data).then((result) => {
        if (result.code == 200) {
          this.$message.success('登录成功');
          window.sessionStorage.setItem('gc_refresh_token', result.result.token)
        } else {
          this.$message.error('登录失败');
          this.handleChangeCheckCode();
        }
      }).catch(() => {
        this.$message.error('登录失败');
        this.handleChangeCheckCode();
      })
    },
    // 数据类型下拉
    dbTypeChange(row) {

      // {label: 'String', value: 'string'}, //默认长度255
      // {label: 'Datetime', value: 'Datetime'},//默认长度 0
      // {label: 'Double', value: 'double'}, //默认长度10
      // {label: 'Integer', value: 'int'}, //默认长度10
      // {label: 'Boolean', value: 'int'}, //默认长度10 布尔型用int代替
      switch(row.dbType) {
           case 'string':
             row.dbLength = 255;
             row.fieldShowType = "text";
             break;
        case 'Datetime':
          row.dbLength = 0;
          row.fieldShowType = "text";
          break;
        case 'double':
          row.dbLength = 10;
          row.fieldShowType = "text";
          break;
        case 'integer':
          row.dbLength = 10;
          row.fieldShowType = "text";
          break;
        case 'boolean':
          row.dbLength = 10;
          row.fieldShowType = "text";
          break;
      }

    /*  if (row.dbType == 'string') {
        row.dbLength = 255;
        row.fieldShowType = "text";
      } else {
        row.dbLength = 0;
        row.fieldShowType = "date";
      }*/
      console.log(row)
    },
    // 提交到数据库
    generatePageCodeClick() {
      if (!this.propsData.tableName) {
        this.$message.error('请输入表名')
        return false
      }
      if (!this.propsData.tableDataParsing) {
        this.$message.error('请输入字段解析')
        return false
      }


      let data = {
        "head": {
          "tableName": this.propsData.enTableName,
          "tableTxt": this.propsData.tableName,
          "tableType": 1,
          // "formCategory": "temp",
          "formCategory": "teamwork",
          "idType": "UUID",
          "isCheckbox": "Y",
          "themeTemplate": "normal",
          "formTemplate": "1",
          "scroll": 1,
          "isPage": "Y",
          "isTree": "N",
          "isDesForm": "N",
          "desFormCode": "",
          "extConfigJson": "{\"reportPrintShow\":0,\"reportPrintUrl\":\"\",\"joinQuery\":0,\"modelFullscreen\":0,\"modalMinWidth\":\"\"}"
        },

        "fields": [
          {
            "dbFieldName": "id",
            "dbFieldTxt": "ID",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "1",
            "fieldShowType": "text",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "19",
            "dbPointLength": "0",
            "dbDefaultVal": "",
            "orderNum": 1,
            "dbType": "int",
            "dbIsKey": "1",
            "dbIsNull": "0",
            "order_num": 0
          },
          {
            "dbFieldName": "CREATOR",
            "dbFieldTxt": "创建者",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "0",
            "fieldShowType": "text",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "50",
            "dbPointLength": "0",
            "dbDefaultVal": "1",
            "orderNum": 3,
            "dbType": "string",
            "dbIsKey": "0",
            "dbIsNull": "1",
            "order_num": 2
          },
          {
            "dbFieldName": "UPDATER",
            "dbFieldTxt": "更新者",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "0",
            "fieldShowType": "text",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "50",
            "dbPointLength": "0",
            "dbDefaultVal": "1",
            "orderNum": 5,
            "dbType": "string",
            "dbIsKey": "0",
            "dbIsNull": "1",
            "order_num": 4
          },

          {
            "dbFieldName": "DELETED",
            "dbFieldTxt": "删除标识",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "0",
            "fieldShowType": "text",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "10",
            "dbPointLength": "0",
            "dbDefaultVal": "0",
            "orderNum": 7,
            "dbType": "int",
            "dbIsKey": "0",
            "dbIsNull": "0",
            "order_num": 6
          },
          {
            "dbFieldName": "TENANT_ID",
            "dbFieldTxt": "租户ID",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "1",
            "fieldShowType": "text",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "10",
            "dbPointLength": "0",
            "dbDefaultVal": "1",
            "orderNum": 9,
            "dbType": "int",
            "dbIsKey": "0",
            "dbIsNull": "0",
            "order_num": 8
          },
          {
            "dbFieldName": "CREATE_TIME",
            "dbFieldTxt": "创建时间",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "0",
            "fieldShowType": "datetime",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "20",
            "dbPointLength": "0",
            "dbDefaultVal": "",
            "orderNum": 11,
            "dbType": "Datetime",
            "dbIsKey": "0",
            "dbIsNull": "1",
            "order_num": 10
          },
          {
            "dbFieldName": "UPDATE_TIME",
            "dbFieldTxt": "更新时间",
            "queryDictField": "",
            "queryDictText": "",
            "queryDefVal": "",
            "queryDictTable": "",
            "queryConfigFlag": "0",
            "mainTable": "",
            "mainField": "",
            "fieldHref": "",
            "dictField": "",
            "dictText": "",
            "fieldValidType": "",
            "fieldMustInput": "0",
            "dictTable": "",
            "fieldLength": "200",
            "fieldDefaultValue": "",
            "fieldExtendJson": "",
            "converter": "",
            "isShowForm": "0",
            "isShowList": "0",
            "sortFlag": "0",
            "isReadOnly": "0",
            "fieldShowType": "datetime",
            "isQuery": "0",
            "queryMode": "single",
            "dbLength": "20",
            "dbPointLength": "0",
            "dbDefaultVal": "",
            "orderNum": 13,
            "dbType": "Datetime",
            "dbIsKey": "0",
            "dbIsNull": "1",//1可以为空 0必填
            "order_num": 12
          }

        ],
        "indexs": [],
        "deleteFieldIds": [],
        "deleteIndexIds": []
      }

      for (let i = 0; i < this.propsData.fieldArray.length; i++) {

        let jsonData = {
          "dbFieldName": this.propsData.fieldArray[i].enData,
          "dbFieldTxt": this.propsData.fieldArray[i].zhData,
          "queryDictField": "",
          "queryDictText": "",
          "queryDefVal": "",
          "queryShowType": "text",
          "queryDictTable": "",
          "queryConfigFlag": "0",
          "mainTable": "",
          "mainField": "",
          "fieldHref": "",
          "dictField": "",
          "dictText": "",
          "fieldValidType": "",
          "fieldMustInput": "0",
          "dictTable": "",
          "fieldLength": "200",
          "fieldDefaultValue": "",
          "fieldExtendJson": "",
          "converter": "",
          "isShowForm": "1",
          "isShowList": "1",
          "sortFlag": "0",
          "isReadOnly": "0",
          "fieldShowType": this.propsData.fieldArray[i].fieldShowType,
          "isQuery": "0",
          "queryMode": "single",
          "dbLength": this.propsData.fieldArray[i].dbLength,
          "dbPointLength": 0,
          "dbDefaultVal": "",
          "orderNum": 15 + i,
          "dbType": this.propsData.fieldArray[i].dbType,
          "dbIsKey": "0",
          "dbIsNull": "1",
          "order_num": 14 + i
        }
        data.fields.push(jsonData)
      }


      this.$nbcioAddAll(data).then((result) => {
        if (result.code == 200) {
          this.$message.success('提交成功');
        } else {
          this.$message.error('提交失败');
        }
      }).catch(() => {
        this.$message.error('提交失败');
      })
    },
    // 百度api翻译
    toEn(text, type) {
      return new Promise((resolve, reject) => {
        const url = 'https://api.fanyi.baidu.com/api/trans/vip/translate';
        const appid = '20220928001356991';//appid
        const salt = this.suijishu();
        const secretKey = 'OLUtQ8cYX3EptRCLH24o';//秘钥
        let str = appid + text + salt + secretKey
        let sign = md5(str)


        jsonp(url, {
          q: text,
          from: 'auto',
          to: 'en',
          appid: appid,
          salt: salt,
          sign: sign,
        }).then(res => {
          let translatedText = res.trans_result[0].dst.replace(/\s/g, '_').toLowerCase()
          if (type == 1) {
            this.propsData.enTableName = 'gc_' + translatedText;
          } else {
            resolve(translatedText)
          }
        }).catch(err => {
          reject(err)
          console.log('err', err);
        })

      })
    },

    // 随机数
    suijishu() {
      let Randnum = '';
      for (let i = 0; i < 10; i++) {
        Randnum += Math.floor(Math.random() * 10);
      }
      return Randnum
    },

    // 开始翻译
    async startParsingClick() {
      if (!this.propsData.tableDataParsing) {
        this.$message.error('请输入字段解析')
        return false
      }
      this.propsData.fieldArray = [];
      let dataParsing = this.propsData.tableDataParsing.split('、');
      for (let i = 0; i < dataParsing.length; i++) {
        let res = await this.toEn(dataParsing[i]);
        let jsonData = {
          zhData: dataParsing[i],
          enData: res,
          dbType: "string",
          dbLength: 255,
          fieldShowType: "text",
          dbIsNull: "0", //0必填 1可以为空
        }
        this.propsData.fieldArray.push(jsonData);
      }
    },

    // 暂存当前生成数据
    temporaryStorage1() {
    },
    // 读取前面暂存的数据
    temporaryStorage2() {
    },
    // 初始化
    initializationClcik() {
      this.$router.go(0);
    }
  },
};
</script>

<style lang="scss" scoped>

</style>
